<template>
    <div class="user-info-form asset-info-form">
      <el-form label-width="150px" :model="naturalWaterInfoForm" :rules="naturalWaterInfoFormRules" ref="naturalWaterInfoForm" @submit.native.prevent>
        <el-form-item label="联网单位：" prop='orgIds'>
          <el-select filterable v-model="naturalWaterInfoForm.orgIds" @change="getFcfSelectList()">
            <el-option
              v-for="item in orgList"
              :key="item.organizationId"
              :label="item.shortName"
              :value="item.organizationId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="消防水源名称："  prop='name'>
          <el-input
            v-model="naturalWaterInfoForm.name"
            clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="位置："  prop='location'>
          <el-input
            v-model="naturalWaterInfoForm.location"
            clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="经度："  prop='lon'>
          <el-input
            v-model="naturalWaterInfoForm.lon"
            clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="纬度："  prop='lat'>
          <el-input
            v-model="naturalWaterInfoForm.lat"
            clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="选取经纬度：">
            <div id="NaturalWaterInfoBaiduMap" style="width:100%;height:300px"></div>
            <input id="nwUnitName_mapInput" class="form-control" v-model="valtemp" placeholder="请输入地点"/>
        </el-form-item>
        <el-form-item label="面积："  prop='area'>
          <el-input
            v-model="naturalWaterInfoForm.area"
            clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="关联探测器：" prop="fcfsId">
          <el-select v-model="naturalWaterInfoForm.fcfsId" id="defaultFcStructId"
            placeholder="请选择关联探测器"
            filterable
            :filter-method="getFcfSelectList"
            :loading="relateFcIdsSelectloading">
            <el-option
              v-for="item in relateFcOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
            <el-pagination
              @current-change="handleCurrentChange"
              :current-page.sync="relateFcPageIndex"
              small
              layout="total, prev, pager, next"
              :total="relateFcTotal">
            </el-pagination>
          </el-select>
        </el-form-item>

        <el-form-item label="现场图片：" prop='url'>
          <el-upload
            :action="QINIUUPLOADURL"
            :multiple="false"
            ref="upload"
            list-type="picture-card"
            :data="qiniuData"
            :on-success="handleAvatarSuccess"
            :on-remove="handleRemovePic"
            :on-error="handleError"
            :before-upload="beforeAvatarUpload"
            :on-preview="$imgPreview"
            :file-list="qiniuData.fileList"
            :limit="1"
            :on-exceed="handleExceed"
            accept="image/gif,image/jpeg,image/jpg,image/bmp,image/png">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label-width="0" class="verifyidentity-button">
          <el-button @click.stop="closeFun(false)" round>取消</el-button>
          <el-button type="primary" @click="saveNaturalWaterInfo('naturalWaterInfoForm')" round>保存</el-button>
        </el-form-item>
      </el-form>
    </div>
</template>
<script>
import BMap from 'BMap'
import util from '@/utils/util'
import { qnToken} from '@/api/api'
import { getOrgList } from '@/api/org'
import { updateNaturalWaters, getFcfSelectList } from '@/api/sysConfig'
import { setTimeout } from 'timers'

var mapWb
export default {
    name: 'NaturalWaterInfo',
    props: {
      naturalWaterInfo: {
          type: Object
      },
      closeFun: {
          type: Function,
          required: true
      }
    },
  data(){
    return {
      orgList: [],
      //选中的数据
      valtemp: '',
      qiniuData:{//上传图片携带的参数
        token : "",
        key : "",
        fileList:[],
      },
      // 表单数据
      naturalWaterInfoForm: {
        name: '',
        location: '',
        lat: '',
        lon: '',
        area: '',
        fcfName: '',
        url: '',
        orgIds: '',
        fcfsId: ''
      },
      // 表单校验
      naturalWaterInfoFormRules: {
        orgIds: [
          { required: true, message: '请输入联网单位', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入消防水源名称', trigger: 'change' }
        ]
      },
      // 关联探测器
      relateFcIdsSelectloading: false,
      relateFcOptions: [],
      relateFcPageIndex: 1,
      relateFcTotal: 0
    }
  },

  created() {
    let that = this
    that.getToken()
    // 获取业主单位信息
    getOrgList({
      queryType: 0
    }).then(res => {
      if (res.status = 200) {
        if (!that.naturalWaterInfo.id) {
          that.naturalWaterInfoForm.orgIds = res.data[0].organizationId
          that.getFcfSelectList()
        }
        that.orgList = res.data
      }
    })
    that.$nextTick(() => {
      // 如果有历史值，设置回显
      if (that.naturalWaterInfo.id) {
        that.naturalWaterInfoForm.id = that.naturalWaterInfo.id
        that.naturalWaterInfoForm.name = that.naturalWaterInfo.name
        that.naturalWaterInfoForm.location = that.naturalWaterInfo.location
        that.naturalWaterInfoForm.lat = that.naturalWaterInfo.lat
        that.naturalWaterInfoForm.lon = that.naturalWaterInfo.lon
        that.naturalWaterInfoForm.area = that.naturalWaterInfo.area
        that.naturalWaterInfoForm.orgIds = that.naturalWaterInfo.organizationId
        if(that.naturalWaterInfo.fcfsId != 0)
        that.naturalWaterInfoForm.fcfsId = that.naturalWaterInfo.fcfsId
        that.getFcfSelectList()
        // 设置上传图片初始值
        that.naturalWaterInfo.url ? $.each(that.naturalWaterInfo.url.split(','), (index, url) => {
          that.qiniuData.fileList.push({
            name: that.naturalWaterInfo.id + index,
            url: url
          })
        }) : ''
      }
      // 初始化地图
      that.initMap()
      /*
      * 解决带分页的下拉框回显值不在首页无法显示label问题
      */
      setTimeout(()=>{
        if(that.naturalWaterInfo.fcfName) {
          let $tags = $('#defaultFcStructId')
          let nameList = that.naturalWaterInfo.fcfName.split(',')
          for (let i=0, len=$tags.length; i < len; i++) {
            $tags[i].value = nameList[i]
          }
        }
      }, 100)
    })
  },

  methods: {
    // 获取关联探测器
    getFcfSelectList(name, pageChange) {
      let that = this
      // 重新搜索时页码复原   
      if(!pageChange) {
        this.relateFcPageIndex = 1
      }
      let parames = {
        fbsId: 0,
        organizationId: that.naturalWaterInfoForm.orgIds,
        parentId: 0,
        pageIndex: this.relateFcPageIndex - 1,
        pageSize: 10,
        name: name || ''
      }
      that.relateFcIdsSelectloading = true
      getFcfSelectList(parames).then(res => {
        if(res.status === 200) {
          that.relateFcOptions = res.data
          that.relateFcTotal = res.total
        }
        that.relateFcIdsSelectloading = false
      })
    },
    // 地图初始化
    initMap() {
      let that = this
      var geoc = new BMap.Geocoder()
      //选取经纬度
      mapWb = new BMap.Map("NaturalWaterInfoBaiduMap")
      mapWb.enableScrollWheelZoom() // 允许缩放
      mapWb.clearOverlays() // 先清除地图上的点
      mapWb.enableKeyboard() // 启用键盘上下左右键移动地图
      mapWb.setDefaultCursor("crosshair") // 设置鼠标样式

      //经纬度画线
      if(that.naturalWaterInfo.lon && that.naturalWaterInfo.lat){
        var new_point1 = new BMap.Point(that.naturalWaterInfo.lon, that.naturalWaterInfo.lat);
        var marker1 = new BMap.Marker(new_point1);  // 创建标注
        mapWb.addOverlay(marker1);              // 将标注添加到地图中
        mapWb.centerAndZoom(new_point1,16);
        //mapWb.panTo(new_point1);
      }else{
        var position = new BMap.Point(116.331398,39.897445);
        mapWb.centerAndZoom(position, 16);
      }

      mapWb.addEventListener("click", function(e){
        // 通过点击百度地图，可以获取到对应的point, 由point的lng、lat属性就可以获取对应的经度纬度
        var pt = e.point;
        geoc.getLocation(pt, function(rs){
          // addressComponents对象可以获取到详细的地址信息
          var addComp = rs.addressComponents;
          var addr = addComp.province +","+ addComp.city +","+addComp.district +","+ addComp.street +","+ addComp.streetNumber
          // 打点
          mapWb.clearOverlays() // 先清除地图上的点
          var marker = new BMap.Marker(pt);  // 创建标注
          mapWb.addOverlay(marker);              // 将标注添加到地图中
          // 经纬度设置值
          that.naturalWaterInfoForm.location = addr
          that.naturalWaterInfoForm.lon = pt.lng
          that.naturalWaterInfoForm.lat = pt.lat
        })
      })
      setTimeout(() => {
        that.mapSearch()
      }, 1000)
    },
    // 搜索经纬度
    mapSearch() {
      var acSearch = new BMap.Autocomplete(
        {'input' : 'nwUnitName_mapInput', 'location' : mapWb}
      );
      acSearch.setInputValue(this.valtemp);
      acSearch.addEventListener("onconfirm", function(e) { //鼠标点击下拉列表后的事件
        var _value = e.item.value;
        var myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
        var local = new BMap.LocalSearch( mapWb, { //智能搜索
          onSearchComplete: function(results){
            var position=results.getPoi(0);//得到标注点坐标
            var lng = position.point.lng;
            var lat = position.point.lat;
            var gpsPoint = new BMap.Point(lng,lat);
            mapWb.centerAndZoom(gpsPoint,16);
          }
        });
        local.search(myValue);
      });
    },

    getToken(){  //上传之前获取 token
      qnToken({}).then((result) => {
        this.qiniuData.token= result.data
      })
    },
    beforeAvatarUpload: function(file){//重命名和校验
      var fielLocal = file.name.split(".")
      var fielType = "." + fielLocal[fielLocal.length-1]
      var fielLocalName = fielLocal[0]
      this.qiniuData.key = 'ilink'+'_'+new Date().getTime()+fielType
      //this.qiniuData.key = file.name;
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt20M = file.size / 1024 / 1024 < 20;
      if (!isJPG && !isPNG) {
        this.$message.error("图片只能是 JPG/PNG 格式!")
        return false;
      }
      if (!isLt20M) {
        this.$message.error("图片大小不能超过 20MB!")
        return false;
      }
    },
    handleAvatarSuccess: function(res, file, fileList) {//上传成功
      this.qiniuData.fileList = fileList
    },
    handleRemovePic: function(file, fileList) {//删除成功
      this.qiniuData.fileList = fileList
    },
    handleError: function(res) {
      this.$message({
        message: "上传失败",
        duration: 2000,
        type: "warning"
      })
    },
    handleExceed(files, fileList) {//文件超出个数限制时的钩子
      this.$message.warning(`只能上传1张图片！`)
    },
    handleCurrentChange(currentpage) {
      this.relateFcPageIndex = currentpage
      this.getFcfSelectList($('#defaultFcStructId .el-select__input').val(), true)
    },
    // 保存
    saveNaturalWaterInfo(formName) {
      // 阻止事件冒泡
      event.stopPropagation()
      let that = this
      let type = 1
      let parames = {}
      // 校验表单
      that.$refs[formName].validate((valid) => {
        if(valid) {
          parames = {
            name: that.naturalWaterInfoForm.name,
            url: util.ilinkArrHandle.getqiniuPicUrlArr(that.qiniuData.fileList).toString(),
            area: that.naturalWaterInfoForm.area,
            id: that.naturalWaterInfo.id,
            fcfsId:that.naturalWaterInfoForm.fcfsId,
            lat:that.naturalWaterInfoForm.lat,
            lon:that.naturalWaterInfoForm.lon,
            location:that.naturalWaterInfoForm.location,
            organizationId:that.naturalWaterInfoForm.orgIds
          }
          if(that.naturalWaterInfo.id==null){
              parames.id = 0
          }
          // 调用保存接口
          updateNaturalWaters(parames).then(res => {
            if(res.status === 200) {
              that.$message({
                message: '保存成功！',
                type: 'success'
              })
              // 关闭弹框
              that.closeFun(true)
            } else {
              that.$message({
                message: '保存失败！',
                type: 'warning'
              })
            }
          })
        } else {
          return false
        }
      })
    },
  }
}
</script>
<style lang="scss">
  #nwUnitName_mapInput {
      position: absolute;
      left: 5%;
      top: 8px;
      padding: 0 10px;
      width: 50%;
      background-color: rgba(255, 255, 255, 0.8);
      height: 38px;
      color: #333;
      border: 0;
      border-top: 1px solid #eee;
      border-left: 1px solid #eee;
      border-right: 1px solid #eee;
      border-radius: 2px 0 0 2px;
      box-shadow: 1px 1.5px 1px rgba(0,0,0,.25);
    }

  .tangram-suggestion-main {
    z-index: 9999999999;
  }
</style>
